import type { ProColumns } from '@ant-design/pro-components';
import {ActionType, EditableProTable, nanoid, PageContainer, ProForm, ProFormText} from '@ant-design/pro-components';
import {Form, message, Card, Typography, Row, Col, Space, DatePicker, Button, Upload, Modal} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import { history } from 'umi';
import {
  DisciInfluenceApi,
  DownloadApi,
  FillApi, GetSaveApi, SaveApi,
  SchoolCheckShow,
  ShowApi,
  UploadApi
} from "@/services/School/SchoolApi";
import {ServerMessages} from "@/services/ServerMessages";
import {getYearMonth, getYear, ShowError} from "@/utils/format";
import {DownloadOutlined, UploadOutlined} from "@ant-design/icons";
import Submitter from "@/pages/Syl/Common/Submitter";
import moment from "moment";


const { Text } = Typography;

type DataSourceType = {
  id: React.Key;
  head_name?: string;
  cour_name?: string;
  cour_type?: string;
  appro_year?: string;
};

const defaultData: DataSourceType[] = [
  {
    id: nanoid(),
    head_name: '',
    cour_name: '',
    cour_type: undefined,
    appro_year: undefined,
  },
  {
    id: nanoid(),
    head_name: '',
    cour_name: '',
    cour_type: undefined,
    appro_year: undefined,
  },
  {
    id: nanoid(),
    head_name: '',
    cour_name: '',
    cour_type: undefined,
    appro_year: undefined,
  },
  {
    id: nanoid(),
    head_name: '',
    cour_name: '',
    cour_type: undefined,
    appro_year: undefined,
  },
];

const columns: ProColumns<DataSourceType>[] = [
  {
    title: '课程类别',
    dataIndex: 'cour_type',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
    valueEnum: {
      "国家级一流本科课程":"国家级一流本科课程",
      "国家级课程思政示范课程":"国家级课程思政示范课程",
      "教育部来华留学英语授课品牌课程":"教育部来华留学英语授课品牌课程",
      "中国专业学位教学案例中心入库案例课程":"中国专业学位教学案例中心入库案例课程",
    }
  },
  {
    title: '课程名称',
    dataIndex: 'cour_name',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
  },
  {
    title: '负责人',
    dataIndex: 'head_name',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
  },
  {
    title: '批准年度',
    dataIndex: 'appro_year',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
    renderFormItem: () => <DatePicker picker="year" />,

  },
  {
    title: '操作',
    valueType: 'option',
  },
];

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );
  const [dataSource, setDataSource] = useState<DataSourceType[]>(() => defaultData);
  const [editForm] = Form.useForm()
  const download = '2_2_2_3'
  const status_is_show = history.location.query.flag === 'display'
  const status_is_check = history.location.query.id && history.location.query.fill_id
  const actionRef = useRef<ActionType>();
  const handleSaveBtn = () => {
    console.log("@Save", download)
    const data = {
      fill_id: download,
      data: dataSource
    }
    console.log("@请求数据", data)
    SaveApi('/api/temp-save', data).then(response => {
      if (response.status === 0) {
        Modal.success({
          title: <span>保存成功！</span>,
          onOk() {
            window.location.reload()
          }
        })

      } else {
        ShowError(response.message)
      }
    }, () => {
      ShowError(ServerMessages.error_message)
    })
  }
  //上传
  const upload = UploadApi('/api/index/cultivate-talents/progress/major-class/nation-counts-template',
    (info) => {
      console.log("@success", info)
      if (info.file.response.status === 0) {
        const data = info.file.response.data["data_"+download]
        for (let i = 0; i < data.length; i++) {
          data[i].id = nanoid()
          data[i].appro_year = moment(data[i].appro_year, 'YYYY')
        }
        setDataSource(data)
        var id_arr = []
        for (let i = 0; i < data.length; i++) {
          id_arr.push(data[i].id)
        }
        setEditableRowKeys(id_arr)
      } else {
        ShowError(info.file.response.message)
      }
    })


  // 更新
  const [reload, setReload] = useState(false)
  useEffect(() => {
    // 插入
    if (status_is_check) {
      // 审核时加载内容
      SchoolCheckShow(history.location.query.id, history.location.query.fill_id)
        .then(response => {
          console.log(response)
          if (response.status === 0) {
            for (let i = 0; i < response.message.length; i++) {
              response.message[i].id = nanoid()
              // response.message[i].appro_year = response.message[i].appro_year ? moment(response.message[i].appro_year, 'YYYY') : undefined
            }
            setDataSource(response.message)
            // resolve({data: response.message})
          } else {
            // resolve(true)
          }
        })
    } else if (status_is_show) {
      // 查看时加载内容
      ShowApi(download).then(response => {
        console.log("@response", response)
        if (response.status === 0) {
          setDataSource(response.data)
          // resolve({data: response.data})
        }
      })
      // resolve(true)
    } else {
      // resolve({data: dataSource})
      GetSaveApi('/api/show-temp-save', download).then(response => {
        console.log("@response", response)
        if (response.status === 0) {
          for (let i = 0; i < response.data.length; i++) {
            response.data[i].id = nanoid()
            response.data[i].appro_year = response.data[i].appro_year ? moment(response.data[i].appro_year, 'YYYY') : undefined
          }
          setDataSource(response.data);
          var id_arr = []
          for (let i = 0; i < response.data.length; i++) {
            id_arr.push(response.data[i].id)
          }
          setEditableRowKeys(id_arr)
        } else {
          setDataSource(dataSource)
          // resolve({data: dataSource})
        }
      })
    }
    console.log("@update", actionRef.current, dataSource)
  }, [reload])

  // useEffect(() => {
  //   console.log("@editable", dataSource)
  //   for (let i = 0; i < dataSource.length; i++) {
  //     actionRef.current.startEditable(dataSource[i].id);
  //   }
  // }, [dataSource])

  return (
    <PageContainer
      title="国家级一流课程建设情况"
      content={<Typography.Text type="danger">1. 监测点内涵：2021年1月1日至今，学科作为主要建设单位，获批课程建设情况。
        <br/>2. 课程类别：国家级一流本科课程、国家级课程思政示范课程，教育部来华留学英语授课品牌课程、中国专业学位教学案例中心入库案例。
        <br/>3. 批准年度：请用“YYYY”填写。
        <br/>4. 仅填写当前填报周期内新增的数据，如有删减，请告知学校管理员。
      </Typography.Text>}>
      <Card bordered={false}>
        <ProForm
          onFinish={async () => {
            if (dataSource.length === 0) {
              message.warn("请输入内容")
              return {}
            }
            return new Promise((resolve => {

              for (let i = 0; i < dataSource.length; i++) {
                dataSource[i].appro_year = getYear(dataSource[i].appro_year)
              }

              editForm.validateFields().then(() => {
                const dataObj = {
                  'data_2_2_2_3': dataSource
                }
                console.log('@请求数据', dataObj)

                FillApi('/api/index/cultivate-talents/progress/major-class/nation-counts',
                  dataObj, (response) => {
                    message.success(response.message)
                    history.push('/cultivate-talents/progress')
                    resolve(true)
                  }, (response) => {
                    ShowError(response.message)
                    resolve(false)
                  }, () => {
                    ShowError(ServerMessages.error_message)
                    resolve(false)
                  })

              }, () => {
                resolve(false)
              })
            }))
          }}
          submitter={{
            render: (props, doms) => {
              return <Submitter
                upload={upload}
                download={download}
                doms={doms}
                save={handleSaveBtn}
              />
            },
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'none',
              },
            },
            submitButtonProps: {
              style: {
                marginLeft: '-8px'
              }
            },
          }}
        >
          <EditableProTable<DataSourceType>
            pagination={{
              pageSize: 10
            }}
            actionRef={actionRef}
            value={dataSource}
            onChange={setDataSource}
            // request={async () => {
            //
            //   // 如果是审核或者查看,则异步加载内容
            //   return new Promise(resolve => {
            //     if (status_is_check) {
            //       // 审核时加载内容
            //       SchoolCheckShow(history.location.query.id, history.location.query.fill_id)
            //         .then(response => {
            //           console.log(response)
            //           if (response.status === 0) {
            //             resolve({data: response.message})
            //           } else {
            //             resolve(true)
            //           }
            //         })
            //     } else if (status_is_show) {
            //       // 查看时加载内容
            //       ShowApi(download).then(response => {
            //         console.log("@response", response)
            //         if (response.status === 0) {
            //           resolve({data: response.data})
            //         }
            //       })
            //       // resolve(true)
            //     } else {
            //       // resolve({data: dataSource})
            //       GetSaveApi('/api/show-temp-save', download).then(response => {
            //         console.log("@response", response)
            //         if (response.status === 0) {
            //           for (let i = 0; i < response.data.length; i++) {
            //             response.data[i].id = nanoid()
            //             response.data[i].appro_year = response.data[i].appro_year ? moment(response.data[i].appro_year, 'YYYY') : undefined
            //           }
            //           resolve({data: response.data})
            //           for (let i = 0; i < response.data.length; i++) {
            //             actionRef.current.startEditable(response.data[i].id)
            //           }
            //           setDataSource(response.data)
            //         } else {
            //           resolve({data: dataSource})
            //         }
            //       })
            //     }
            //   })
            // }}
            columns={columns}
            rowKey="id"
            recordCreatorProps={{
              newRecordType: 'dataSource',
              record: () => ({
                id: nanoid(),
              }),
              style: {
                display: status_is_show || status_is_check ? 'none' : 'block',
              },
            }}
            editable={{
              type: 'multiple',
              form: editForm,
              editableKeys,
              actionRender: (row, config, defaultDoms) => {
                return [defaultDoms.delete];
              },
              onValuesChange: (record, recordList) => {
                if (record) {
                  setDataSource(recordList);
                } else {
                  // recordList 代表表单的真实数据，但是在空值检测时会变成空值，
                  // 所以只在有输入变化时同步到 DataSource，可以通过 record 来判断是否有输入。
                  // 执行删除操作时，DataSource 应该删掉 recordList 中不存在的项目。
                  let index_list = []
                  for (let i = 0; i < recordList.length; i++) {
                    index_list.push(recordList[i].id)
                  }
                  let newDataSource = []
                  for (let i = 0; i < dataSource.length; i++) {
                    if (index_list.indexOf(dataSource[i].id) !== -1) {
                      newDataSource.push(dataSource[i])
                    }
                  }
                  setDataSource(newDataSource)
                }
              },
              onChange: setEditableRowKeys,
            }}
            style={{marginBottom: 20}}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};
